<!doctype html>
<html lang=en>
<head>
  <meta charset=UTF-8>
  <meta name=viewport
        content=width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0>
  <meta http-equiv=X-UA-Compatible content=ie=edge>
  <title>Document</title>
</head>
<body>
  <script>
    // 已知数据
    const data = [
      {
        parentId: null,
        id: 1,
        name: "张三",
        children: [
          {
            parentId: 1,
            id: 2,
            name: "李四",
            children: []
          },
          {
            parentId: 1,
            id: 4,
            name: "黎明",
            children: [
              {
                parentId: 4,
                id: 5,
                name: "张学友",
                children: []
              }
            ]
          }
        ]
      },
      {
        parentId: null,
        id: 3,
        name: "刘德华",
        children: []
      }
    ]

    // 实现函数, 给定一个id, 返回节点数据    findTreeNode(data, 4)  返回=>
    /*
          {
            parentId: 1,
            id: 4,
            name: 黎明,
            children: [
              {
                parentId: 4,
                id: 5,
                name: 张学友,
                children: []
              }
            ]
          }
     */
    function findTreeNode(list, parentId) {
      const currentLevelList = list

      if (!currentLevelList.length) {return null}

      // 1.在当前层级寻找
      const item = currentLevelList.find(item => item.id === parentId)
      if (item) {
        return item
      } else {
        // 2.当前层级没有找到, 把当前层级的children组合成一个新的list, 组成一个下一层级, 递归调用
        const nextLevelList = currentLevelList.reduce((prev, curr) => {
          return prev.concat(curr.children)
        }, [])
        return findTreeNode(nextLevelList, parentId)
      }
    }

    console.log(findTreeNode(data, 4))
  </script>
</body>
</html>
